﻿using AutoWelding.BLL;
using AutoWelding.Models;
using AutoWelding.Utils;
using AutoWelding.Views.Manual;
using AutoWelding.Views.Visual;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AutoWelding.Views
{
    public partial class MainPageForm : Form
    {
        //引用浮动窗体
        private VisualForm_副本 _floatForm;
        //配方
        private readonly RecipesBLL recipesBLL = new RecipesBLL();
        // 用于控制机器人任务的暂停和恢复
        private ManualResetEventSlim _robotPauseEvent = new ManualResetEventSlim(true);
        // 用于取消机器人任务
        private CancellationTokenSource _robotCancellationTokenSource;

        // 用于控制转接台和上下料任务的暂停和恢复
        private ManualResetEventSlim _transferPauseEvent = new ManualResetEventSlim(true);
        // 用于取消转接台和上下料任务
        private CancellationTokenSource _transferCancellationTokenSource;

        public MainPageForm()
        {
            InitializeComponent();
        }

        private void MainPageForm_Load(object sender, EventArgs e)
        {
            //初始化产品数量下拉框
            InitProductCount();
            //初始化配方下拉框
            InitRecipesCbx();

            //string productName = CreateProductName();
            //label_productName.Text = productName;
        }

        /// <summary>
        /// 结束按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_end_Click(object sender, EventArgs e)
        {
            // 清理机器人线程资源
            _robotCancellationTokenSource?.Cancel();
            _robotPauseEvent?.Set();
            _robotPauseEvent?.Dispose();
            _robotCancellationTokenSource?.Dispose();

            // 清理内部设备工作线程资源
            _transferCancellationTokenSource?.Cancel();
            _transferPauseEvent?.Set();
            _transferPauseEvent?.Dispose();
            _transferCancellationTokenSource?.Dispose();
        }
        /// <summary>
        /// 运行(开始)按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_run_Click(object sender, EventArgs e)
        {
            //Debug.WriteLine("开始运行---" + "料盘1产品数量：" +  cbx_productCount_01.Text + "---料盘2产品数量：" + cbx_productCount_02.Text);
            //Debug.WriteLine("运行："+ cbx_recipes.Text);
            if (cbx_productCount_01.Text == "0" && cbx_productCount_02.Text == "0" && cbx_productCount_03.Text == "0")
            {
                MessageBox.Show("请选择每个料盘的产品数量。");
                
            }
            else
            {
                if(cbx_recipes.Text == "---请选择---")
                {
                    MessageBox.Show("请选择配方！");
                }
                else
                {
                    AutoRun();
                }
            }
           
        }


        /// <summary>
        /// 打开手动运行页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_manual_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("请手动进行操作！");
            ManualForm manualForm = new ManualForm();
            manualForm.ShowDialog();

        }

        /// <summary>
        /// 打开视觉小窗
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_showFloatForm_Click(object sender, EventArgs e)
        {
            try
            {
                if (_floatForm == null || _floatForm.IsDisposed)
                {
                    _floatForm = new VisualForm_副本();
                    _floatForm.Show();
                }
            }
            catch
            {
                MessageBox.Show("浮动窗体异常");
            }
        }

        /// <summary>
        /// 初始化产品数量
        /// </summary>
        private void InitProductCount()
        {
            try
            {
                var productCounts = new[] { "0", "6", "12" };
                ComboBox[] comboBoxes = {
                cbx_productCount_01,
                cbx_productCount_02,
                cbx_productCount_03
        }       ;

                foreach (var cbx in comboBoxes)
                {
                    if (cbx != null)
                    {
                        cbx.Items.Clear();
                        cbx.Items.AddRange(productCounts);
                        cbx.SelectedIndex = 0;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化产品数量下拉框失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 初始化配方下拉框
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void InitRecipesCbx()
        {

            List<RecipesModel> recipesModels = recipesBLL.GetRecipesList(null, 0, false);
            recipesModels.Insert(0, new RecipesModel() { RecipeId = 0, RecipeName = "---请选择---" });

            cbx_recipes.DataSource = recipesModels;
            cbx_recipes.DisplayMember = "RecipeName";
            cbx_recipes.ValueMember = "RecipeId";
            cbx_recipes.SelectedIndex = 0;
        }

        /// <summary>
        /// 生成产品名称：时间戳+料盘编码+产品批次号
        /// </summary>
        /// <returns></returns>
        private string CreateProductName(String TrayId,String ProductId)
        { 
            //时间戳
            string ProductName = "P" + DateTime.Now.ToString("yyyyMMddHHmmss");       
            //组合产品名称
            ProductName = ProductName + TrayId + ProductId;//时间戳+料盘编码+产品批次号
            return ProductName;
        }




        #region 自动运行方法
        /// <summary>
        /// 自动运行方法
        /// </summary>
        private void AutoRun()
        {
            MessageBox.Show("开始运行！");
            //机器人将拾取料盘上的焊接产品至1号位
            // 启动机器人任务线程
            //机器人工作时，内部系统线程暂停，等待机器人任务结束，内部系统线程恢复运行
 ;
            StartRobotTaskThread();
       
            //启动内部系统工作线程
            StartTransferTaskThread();
        
        }

        #region 机器内部圈焊产品任务线程
        /// <summary>
        /// 转接台送料至圈焊机内部任务线程、以及内部工作
        /// </summary>
        private void TransferAndWorkTask()
        {
            try
            {
                Thread.Sleep(1000);

                // 获取取消令牌
                CancellationToken token = _transferCancellationTokenSource.Token;

                // 检查是否需要取消任务
                if (token.IsCancellationRequested)
                {
                    Debug.WriteLine("转接台任务被取消");
                    return;
                }

                // 等待继续信号（如果被暂停）
                _transferPauseEvent.Wait(token);

                // 转接台送料至圈焊机内部（防护门打开）
                MoveProductToMachine();

                // 检查是否需要取消任务
                if (token.IsCancellationRequested)
                {
                    Debug.WriteLine("转接台任务被取消");
                    return;
                }

                // 等待继续信号（如果被暂停）
                _transferPauseEvent.Wait(token);

                // 上下料部件拾取产品,180°旋转后装夹至旋转台
                PickProductToRotaryTable();

                // 检查是否需要取消任务
                if (token.IsCancellationRequested)
                {
                    Debug.WriteLine("转接台任务被取消");
                    return;
                }
                // 等待继续信号（如果被暂停）
                _transferPauseEvent.Wait(token);
                // 视觉对位系统识别焊缝（CCD拍照 + 偏差计算）
                // 对位是否合格
                if (OffsetCalculate())
                {
                    Debug.WriteLine("视觉对位完成，已暂停机器人任务等待下一步指令");

                    // 可以在这里触发UI更新，提示用户操作
                    this.Invoke((MethodInvoker)delegate {
                        MessageBox.Show("视觉对位完成，请确认后继续操作");
                    });
                }
                else
                {
                    // 对位失败
                    Debug.WriteLine("焊机对位失败！");
                    this.Invoke((MethodInvoker)delegate {
                        MessageBox.Show("焊机对位失败！");
                    });
                }


                Debug.WriteLine("转接台和上下料任务完成");
            }
            catch (OperationCanceledException)
            {
                Debug.WriteLine("转接台任务被取消");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"转接台任务异常: {ex.Message}");
                this.Invoke((MethodInvoker)delegate {
                    MessageBox.Show($"转接台任务异常: {ex.Message}");
                });
            }
        }

        /// <summary>
        /// 启动TransferAndWorkTask()线程
        /// </summary>
        private void StartTransferTaskThread()
        {
            // 初始化取消令牌
            _transferCancellationTokenSource = new CancellationTokenSource();

            Thread transferThread = new Thread(() =>
            {
                TransferAndWorkTask();
            });

            transferThread.IsBackground = true;
            transferThread.Start();
        }

        /// <summary>
        /// 暂停转接台任务
        /// </summary>
        public void PauseTransferTask()
        {
            _transferPauseEvent.Reset();
        }

        /// <summary>
        /// 恢复转接台任务
        /// </summary>
        public void ResumeTransferTask()
        {
            _transferPauseEvent.Set();
        }

        /// <summary>
        /// 取消转接台任务
        /// </summary>
        public void CancelTransferTask()
        {
            _transferCancellationTokenSource?.Cancel();
            _transferPauseEvent.Set();
        }

        /// <summary>
        /// 视觉偏移量计算
        /// </summary>
        /// <returns></returns>
        private bool OffsetCalculate()
        {
            //获取偏移量
            //偏移量范围是否在正负0.1的范围
            return true;
        }

        /// <summary>
        /// 上下料部件拾取产品,180°旋转后装夹至旋转台
        /// </summary>
        private void PickProductToRotaryTable()
        {
            //上下料部件拾取产品，
            //旋转180°
            //装夹至旋转台
            for (int i = 0; i < 10; i++)
            {
                Debug.WriteLine("------------------上下料部件拾取产品，旋转180°，装夹至旋转台----------------");
            }
        }

        /// <summary>
        /// 转接台送料至圈焊机内部（防护门打开）
        /// </summary>
        private void MoveProductToMachine()
        {
            //防护门打开
            Debug.WriteLine("-------防护门打开----------");
            //转接台移动
            Debug.WriteLine("------------------转接台向设备内部移动----------------");
        }
        #endregion


        #region 拾取料盘产品线程

        /// <summary>
        /// 返回有产品的料盘号和产品个数
        /// </summary>
        /// <returns></returns>
        private Dictionary<int, int> CheckTraysWithProducts()
        {
            //定义一个字典存储料盘号和产品个数
            Dictionary<int, int> trayProducts = new Dictionary<int, int>();
            if (cbx_productCount_01.SelectedIndex != 0)
                trayProducts.Add(1, Convert.ToInt32(cbx_productCount_01.SelectedItem));
            if (cbx_productCount_02.SelectedIndex != 0)
                trayProducts.Add(2, Convert.ToInt32(cbx_productCount_02.SelectedItem));
            if (cbx_productCount_03.SelectedIndex != 0)
                trayProducts.Add(3, Convert.ToInt32(cbx_productCount_03.SelectedItem));
            return trayProducts;
        }
        /// <summary>
        /// 机器人将拾取料盘上的焊接产品至1号位
        /// </summary>
        private void RobotPickProductToStationOne()
        {
            try
            {
                Debug.WriteLine("机器人任务开始，暂停内部系统线程");
                PauseTransferTask();

                // 初始化取消令牌
                _robotCancellationTokenSource = new CancellationTokenSource();
                CancellationToken token = _robotCancellationTokenSource.Token;

                // 获取料盘数据
                Dictionary<int, int> trays = new Dictionary<int, int>();
                this.Invoke((MethodInvoker)delegate {
                    trays = CheckTraysWithProducts();
                });

                foreach (var tray in trays)
                {
                    if (token.IsCancellationRequested) break;

                    int trayId = tray.Key;
                    int totalProducts = tray.Value;
                    int pickedCount = 0;

                    while (pickedCount < totalProducts)
                    {
                        if (token.IsCancellationRequested) return;

                        _robotPauseEvent.Wait(token);

                        // 方案二：先查找产品位置，再拾取产品
                        string position = RobotUtils.FindFirstProduct(trayId);
                        if (position != null)
                        {
                            // 拾取产品
                            if (RobotUtils.PickProductAtPosition(trayId, position))
                            {
                                pickedCount++;
                                Debug.WriteLine($"料盘{trayId}已拾取{pickedCount}/{totalProducts}个产品");

                                // 更新主界面产品名称展示
                                this.Invoke((MethodInvoker)delegate {
                                    string productName = CreateProductName($"_{trayId:D2}_", $"_{position}");
                                    label_productName.Text = productName;
                                });
                            }
                        }
                        else
                        {
                            Debug.WriteLine($"料盘{trayId}上没有可拾取的产品");
                            break; // 跳出当前料盘的循环
                        }
                    }
                }

                RobotUtils.RobotMoveToPlace_01();
                GripperUtils.RobotGripperOpen();

                Debug.WriteLine("机器人拾取任务完成");

                // 确保恢复内部系统线程
                ResumeTransferTask();
                Debug.WriteLine("已恢复内部系统线程");

            }
            catch (OperationCanceledException)
            {
                Debug.WriteLine("机器人任务被取消");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"机器人任务异常: {ex.Message}");
                this.Invoke((MethodInvoker)delegate {
                    MessageBox.Show($"机器人任务异常: {ex.Message}");
                });
            }
        }

        /// <summary>
        /// 暂停机器人任务
        /// </summary>
        public void PauseRobotTask()
        {
            _robotPauseEvent.Reset();
        }

        /// <summary>
        /// 恢复机器人任务
        /// </summary>
        public void ResumeRobotTask()
        {
            _robotPauseEvent.Set();
        }

        /// <summary>
        /// 取消机器人任务
        /// </summary>
        public void CancelRobotTask()
        {
            _robotCancellationTokenSource?.Cancel();
            _robotPauseEvent.Set();
        }

        /// <summary>
        /// 启动机器人拾取任务的线程
        /// </summary>
        private void StartRobotTaskThread()
        {
            Thread robotThread = new Thread(() =>
            {
                try
                {
                    RobotPickProductToStationOne();
                }
                catch (OperationCanceledException)
                {
                    Debug.WriteLine("机器人任务被取消");
                }
                catch (Exception ex)
                {
                    this.Invoke((MethodInvoker)delegate {
                        MessageBox.Show($"机器人任务异常: {ex.Message}");
                    });
                }
            });

            robotThread.IsBackground = true;
            robotThread.Start();
        }
        #endregion

        #endregion
    }


}
